'''
Author: SlytherinGe
LastEditTime: 2021-07-31 21:23:31
'''
from pic_sampling import voc_split_image_and_annotation as split
from read_tiff import tiff_16bit_img_read_and_normalize as imgread
import os
import cv2


def generate_from_airsarship_1():

    ROOT = "./../SARShip"
    OUTDIR = "./../ShipOnly"
    WIDTH = 1000
    HEIGHT = WIDTH
    OVERLAP_W = 500
    OVERLAP_H = OVERLAP_W
    IGNORE = True
    listdir = os.listdir(ROOT)
    for father in listdir:
        sons = os.listdir(os.path.join(ROOT, father))
        for son in sons:
            if son.endswith('.xml'):
                ann_file_path = os.path.join(ROOT, father, son)
                print("ann:", ann_file_path)
            elif son.endswith('.tiff'):
                pic_file_path = os.path.join(ROOT, father, son)
                print("pic:",pic_file_path)
        split(imgread, pic_file_path, ann_file_path, OUTDIR, WIDTH, HEIGHT, OVERLAP_W, OVERLAP_H, ignore_empty=IGNORE)


def generate_from_airsarship_2():
    ROOT_DATA = "./../AIR-SARShip-2.0-data"
    OUTDIR = "./../ShipOnly"  
    listdir = os.listdir(ROOT_DATA)  
    for pic in listdir:
        if pic.endswith('.tiff'):
            img_name = pic.split('.')
            img_path = os.path.join(ROOT_DATA, pic)
            img = imgread(img_path)
            cv2.imwrite(os.path.join(OUTDIR, img_name[0] + '.jpg'), img)

def generate_from_LS_SSDD():
    ROOT_DATA = '/media/gejunyao/Disk1/Datasets/LS-SSDD-v1.0-OPEN/VOC2012/JPEGImages_full/'
    ROOT_ANNO = '/media/gejunyao/Disk1/Datasets/LS-SSDD-v1.0-OPEN/VOC2012/Annotations_full/'
    OUTDIR = "/media/gejunyao/Disk1/Customized Datasets/LS-SSDD-720/"  
    WIDTH = 720
    HEIGHT = WIDTH
    OVERLAP_W = 0
    OVERLAP_H = OVERLAP_W
    IGNORE = False
    NUM_OF_PIC = 15

    pic_list = [i for i in range(1,NUM_OF_PIC+1)]
    if not os.path.exists(OUTDIR):
        os.mkdir(OUTDIR)
    if not os.path.exists(os.path.join(OUTDIR, 'JPEGImages')):
        os.mkdir(os.path.join(OUTDIR, 'JPEGImages'))
    if not os.path.exists(os.path.join(OUTDIR, 'Annotations')):
        os.mkdir(os.path.join(OUTDIR, 'Annotations'))
        
    for i in range(2):
        pid = os.fork()
        if pid == 0:
            # child
            pic_list = pic_list[:int(len(pic_list)//2)]
        elif pid > 0:
            # parent
            pic_list = pic_list[int(len(pic_list)//2):]
        else:
            print('fork failed！')
    for i in pic_list:
        pic_file_path = os.path.join(ROOT_DATA, '{:0>2d}'.format(i)+'.jpg')
        ann_file_path = os.path.join(ROOT_ANNO, '{:0>2d}'.format(i)+'.xml')
        print(pic_file_path)
        print(ann_file_path)
        split(cv2.imread, pic_file_path, ann_file_path, OUTDIR, WIDTH, HEIGHT, OVERLAP_W, OVERLAP_H, ignore_empty=IGNORE)

if __name__ == "__main__":
    generate_from_LS_SSDD()
